package com.example.demo1.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.demo1.R;
import com.example.demo1.R.layout;
import com.example.demo1.R.menu;
import com.example.demo1.domain.User;
import com.example.demo1.service.UserService;
import com.example.demo1.utils.ServerUtils;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class ListActivity extends android.app.ListActivity implements
		OnClickListener {

	private UserService userService = new UserService();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SimpleAdapter adapter = new SimpleAdapter(this, getData(),
				R.layout.activity_list, new String[] { "id", "name", "email",
						"img" }, new int[] { R.id.id, R.id.name, R.id.email,
						R.id.img });

		SimpleAdapter.ViewBinder binder = new SimpleAdapter.ViewBinder() {

			@Override
			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (view instanceof TextView) {
					final View button = view;
					view.setOnClickListener(new OnClickListener() {

						LinearLayout linearLayout = (LinearLayout) button
								.getParent();
						TextView tv = (TextView) linearLayout
								.findViewById(R.id.id);

						@Override
						public void onClick(View v) {
							displayToast(tv.getText());
						}
					});
					return false;
				}
				return false;
			}
		};
		adapter.setViewBinder(binder);

		setListAdapter(adapter);

	}

	private List<Map<String, Object>> getData() {
		List<User> users = userService.getUserList(10, 0);
		System.out.println(users);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		for (User user : users) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", user.getId());
			map.put("name", user.getName());
			map.put("email", user.getEmail());
			map.put("img", R.drawable.ic_launcher);
			list.add(map);
		}

		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		if (v instanceof TableRow) {
			TableRow tableRow = (TableRow) v;
			TextView textView = (TextView) tableRow.findViewById(R.id.id);
			displayToast(textView.getText());
		}
	}

	public void displayToast(Object object) {
		Toast.makeText(this, object.toString(), Toast.LENGTH_SHORT).show();

	}

}
